<template>
  <div class="wrap">
    <div class="panel">
      <h2>注册</h2>
      <form class="form" @submit.prevent="submit">
        <!-- 新增：用户名 -->
        <div class="field">
          <label>用户名</label>
          <input
              v-model.trim="username"
              type="text"
              required
              minlength="3"
              maxlength="20"
              pattern="^[A-Za-z0-9_.-]{3,20}$"
              placeholder="3-20位，字母/数字/._-"
          />
        </div>

        <div class="field">
          <label>邮箱</label>
          <input v-model.trim="email" type="email" required />
        </div>

        <div class="field">
          <label>密码</label>
          <input v-model="password" type="password" minlength="6" required />
        </div>

        <button :disabled="loading">注册</button>
        <a class="link" @click.prevent="$router.push('/login')">已有账号？去登录</a>
        <p v-if="msg" class="ok">{{ msg }}</p>
        <p v-if="error" class="err">{{ error }}</p>
      </form>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
export default { name: 'RegisterPage',
  setup(){
    const username = ref('')     // ✨ 新增
    const email = ref('')
    const password = ref('')
    const loading = ref(false)
    const error = ref('')
    const msg = ref('')
    const router = useRouter()
    const auth = useAuthStore()

    const submit = async () => {
      error.value=''; msg.value=''; loading.value=true
      try {
        await auth.register(email.value, password.value, username.value)  // ✨ 传递 username
        msg.value='注册成功，请登录'
        setTimeout(()=>router.replace('/login'), 600)
      } catch (e) {
        error.value = e?.response?.data?.message || '注册失败'
      } finally {
        loading.value=false
      }
    }
    return { username, email, password, loading, error, msg, submit }
  }
}
</script>

<style src="./auth.css" scoped></style>
